import { LoginApi } from "../../api/user";
import { aboutUser } from "../../store/index";
import { getFreeRule } from "../../api/user";
import { getListApi } from "../../api/common";
import { debounce } from "../../utils/debounce";

Page({
  data: {
    scrollTop: 0,
    videoList: [],
    bannerList: [],
    backTopBtn: false,
    videoPlayerList: [],
    refresherCtrl: false,
    isrReq: false, // 判断接口是否请求种，避免重复请求
    listParams: { uid: aboutUser.getUserInfo().userId, vname: "", pageSize: 15, pageNum: 1, tableType: 0 },
  },

  async onLoad() {
    let options = tt.getLaunchOptionsSync();

    aboutUser.saveUserData(options);

    this.LoginFun();
    this.initFun();
  },

  onShow() {
    this.reSetVideoListHis();
  },

  /** 根据 appId 初始化应用信息 */
  initFun() {
    let options = {};
    const EnvInfo = tt.getEnvInfoSync();

    switch (EnvInfo.microapp.appId) {
      // 谷雨
      case "tt41fa3747decef57401":
        options.imId = "1131191387";
        options.appTitle = "谷雨剧场";
        options.adUnitId = "vnpk8yjpfvdrqwmg3c";
        break;
      // 春分
      case "tta1e4d7593ed0156801":
        options.imId = "i_lucky88";
        options.appTitle = "春分剧场";
        options.adUnitId = "7ne7pef8806yj0yr4i";
        break;
      // 觅得小剧场
      case "tt674411f9f875a12c01":
        options.imId = "1670984762";
        options.appTitle = "觅得乐小剧场";
        options.adUnitId = "8ngmeckb0jvobxun2i";
        break;
      // 觅得剧场
      case "tt231655abbc260b9c01":
        options.imId = "knight799872";
        options.appTitle = "觅得剧场";
        options.adUnitId = "vvyvuet48y51qm6zmr";
        break;
      // 小满剧场
      case "ttb1f9c7442ecd057401":
        options.imId = "dycbyk7t0ccl";
        options.appTitle = "小满剧场";
        options.adUnitId = "r1xn1vlz9onu021fp2";
        break;
      // 暖冬剧场
      case "tt419d3720dea9f4e301":
        options.imId = "364879164";
        options.appTitle = "暖冬剧场";
        options.adUnitId = "38ijya9r42hb5ic5bi";
        break;
      // 青瓜剧场
      case "tt1c3a6a878330de6c01":
        options.imId = "182359013";
        options.appTitle = "青瓜剧场";
        options.adUnitId = "sf781490xegeye4xvv";
        break;
      default:
        options.appTitle = "剧场";
    }

    tt.setNavigationBarTitle({ title: options.appTitle });

    aboutUser.saveUserData(options);
  },

  /** 登录 */
  async LoginFun() {
    tt.login({
      force: true,
      success: async ({ code }) => {
        try {
          let data = await LoginApi({ code, appId: tt.getEnvInfoSync().microapp.appId });

          if (data.code == 200) {
            aboutUser.saveUserData({ userId: data.data?.uid, userName: data.data?.nickName });

            this.setData({ refresherCtrl: true });
            this.getListFun();
            this.getFreeRuleFun();
          } else {
            tt.showModal({ title: "登录失败", content: data.message, showCancel: false });
          }
        } catch (error) {
          tt.showModal({ title: "api登录失败", content: error.message, showCancel: false });
        }
      },
      fail: (res) => {
        tt.showModal({ title: "tt登录失败", content: error.message, showCancel: false });
      },
    });
  },

  /** 分页获取首页列表 */
  async getListFun(reset) {
    if (this.data.isrReq) {
      return;
    }

    this.setData({ isrReq: true });

    try {
      let { videoList, listParams } = this.data;

      if (reset) {
        listParams.pageNum = 1;
      } else if (videoList.length) {
        listParams.pageNum += 1;
        this.setData({ listParams });
      }

      const res = await getListApi(this.data.listParams);

      if (res.code != 200 || res.data.length == 0) {
        setTimeout(() => {
          tt.showToast({ icon: "none", title: "没有更多了" });
          this.setData({ refresherCtrl: false, isrReq: false });
        }, 500);
        return;
      }

      setTimeout(() => this.setData({ videoList: reset ? res.data : [...this.data.videoList, ...res.data], refresherCtrl: false, isrReq: false }), 500);
    } catch (err) {
      console.log(err, "获取短剧列表失败");
    }
  },

  /** 根据落地页kid获取视频id跳转 */
  async getFreeRuleFun() {
    // 获取小程序启动参数，判断是否有卡点视频信息，有则跳转至 video 页面
    let options = tt.getEnterOptionsSync();

    aboutUser.addPointFun("openNum"); // 埋点

    if (!options.query?.kid) {
      return;
    }

    let ruleData = await getFreeRule({ kid: options.query?.kid, uid: aboutUser.getUserInfo().userId });

    aboutUser.saveUserData(ruleData.data);

    const vid = ruleData.data?.vid;
    const albumId = ruleData.data?.albumId;
    const episodeId = ruleData.data?.episodeId;

    tt.navigateTo({ url: `/page/playlet-extension/index?seq=1&tt_album_id=${albumId}&tt_episode_id=${episodeId}&vid=${vid}` });
  },

  //跳转新范式编写的播控组件
  goPlayletExtension(e) {
    if (tt.canIUse("getPlayletManager")) {
      const vid = e.currentTarget.dataset?.vid;
      const albumId = e.currentTarget.dataset?.id;
      const episodesId = e.currentTarget.dataset?.episodesid;
      console.log("广场页playletplugin-aid&eid:", albumId, episodesId);
      tt.navigateTo({ url: `/page/playlet-extension/index?seq=1&tt_album_id=${albumId}&tt_episode_id=${episodesId}&vid=${vid}` });
    } else {
      // ... 跳转至开发者自有播放页
      tt.showModal({ title: "提示", content: "请升级宿主版本", showCancel: false });
    }
  },

  /** 滚动到底部加载分页 */
  bindscrolltolower(e) {
    this.getListFun();
  },

  /** 列表刷新 */
  bindrefresherrefresh(e) {
    this.setData({ refresherCtrl: true });
    this.getListFun(true);
  },

  /** 清空搜索 */
  reSearch() {
    let { listParams } = this.data;
    this.setData({ listParams: { ...listParams, vname: "" }, refresherCtrl: true, scrollTop: 0 });
    this.getListFun(true);
  },

  /** 输入框输入事件 */
  bindinput(e) {
    let { listParams } = this.data;
    listParams.vname = e.detail.value;
    this.setData({ listParams });
  },

  /** 回到顶部 */
  backTopFun() {
    this.setData({ backTopBtn: false, scrollTop: 0 });
  },

  /** 滚动事件 */
  scrollFun(e) {
    this.setData({ backTopBtn: e.detail.scrollTop >= 3000 ? true : false });
    debounce(() => this.setData({ scrollTop: e.detail.scrollTop }), 800);
  },

  /** 重置列表历史集 */
  reSetVideoListHis() {
    let { videoList } = this.data;
    let historyData = aboutUser.getUserInfo()?.historyData;

    if (!historyData) {
      return;
    }
    videoList.forEach((item) => item.vid == historyData?.vid && (item.episodeId = historyData.episodeId));

    this.setData({ videoList });
  },
});
